package com.chenjian.controller;

import com.chenjian.common.CommonVO;
import com.chenjian.common.enums.RESPONSE_ENUM;
import com.chenjian.common.utils.BindResultUtils;
import com.chenjian.entity.Module;
import com.chenjian.entity.User;
import com.chenjian.exceptiom.CommonException;
import com.chenjian.service.ModuleService;
import com.chenjian.service.UserService;
import com.chenjian.vo.ModuleAddVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/module")
public class ModuleController {

    @Autowired
    private ModuleService moduleServiceImpl;

    @Autowired
    private UserService userServiceImpl;

    @PostMapping(value = "/add")
    public Object addModule(@RequestBody @Validated ModuleAddVo moduleAddVo, BindingResult bindingResult) {

        BindResultUtils.checkBindingResult(bindingResult);

        User user = userServiceImpl.getById(moduleAddVo.getUserId());
        if (null != user) {
            Module module = new Module();
            module.setModuleName(moduleAddVo.getModuleName());
            module.setUserId(user.getId());
            moduleServiceImpl.save(module);
            return new CommonVO<>(module);
        }
        throw new CommonException("用户不存在或已删除", RESPONSE_ENUM.FAIL_404.getCode());
    }
}
